package com.srwl.mytx.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.core.widget.NestedScrollView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MenuArrayAdapter;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.FileUpLoad;
import com.srwl.mytx.domain.LatLng;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.AgreementDialog;
import com.srwl.mytx.widget.PreviewSelectFilePageView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.DateChooseDialog;
import com.srwl.mytx.widget.PickPicturesListView;
import com.srwl.mytx.utils.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class PublishTopicActivity extends BaseActivity implements PickPictureAdapter.InteractionListener, PreviewSelectFilePageView.GetPhotoViewInfoListener, PermissionsUtils.IPermissionsResult {
    private static String TAG = PublishTopicActivity.class.getSimpleName();
    public static final int REQUEST_CODE_PICTURE_CHOOSE = 1;
    public static final int REQUEST_CODE_RECORD_VIDEO = 2;
    public static final int REQUEST_CODE_LOCATION = 3;
    private static final int SITUATION_FOR_PUBLISH = 102;// 表示拍摄视频的质量和大小都按上限处理
    private float density;
    @BindView(R.id.tv_starting_date)
    TextView tv_startDate;
    @BindView(R.id.tv_stop_date)
    TextView tv_stopDate;
    @BindView(R.id.rv_add_picture)
    PickPicturesListView picturesListView;
    @BindView(R.id.ll_auction)
    View ll_auction;

    @BindView(R.id.et_goods_description)
    EditText et_content;
    @BindView(R.id.et_goods_title)
    EditText et_title;
    @BindView(R.id.tv_price_tag)
    TextView tv_priceTag;
    @BindView(R.id.et_normal_price)
    EditText et_normalPrice;//普通出售商品价格
    @BindView(R.id.et_deposit)
    EditText et_deposit;//保证金
    @BindView(R.id.et_bid_increment)
    EditText et_bidIncrement;
    @BindView(R.id.fl_bigPicture)
    View fl_bigPicture;
    @BindView(R.id.img_bg_black)
    ImageView iv_background;
    @BindView(R.id.title_bar)
    MyTitleBar titleBar;
    @BindView(R.id.rl_normal_price)
    View rl_NormalPrice;
    @BindView(R.id.sv_container)
    NestedScrollView sv_container;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.big_picture_page_view)
    PreviewSelectFilePageView previewSelectFilePageView;
    @BindView(R.id.rl_location)
    RelativeLayout rl_location;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.btn_publish)
    Button btn_publish;
    @BindView(R.id.status_bar)
    View statusBar;

    private GaodeLocationClient location;

    private String str_address;

    private LatLng latLng;
    //视频封面图片
    private String framePicPath;
    //视频大小
    private int videoSize;
    //主题分类
    private Integer topicType;
    private Topic topic = new Topic();
    private int pictureLimit = 9;//默认设置9张图片
    private int videoLimit = 1;//默认设置1个视频
    private ArrayList<MyFile> totalSelectFile = new ArrayList<>();//总的选择图片文件集合，包括本地的和远程的（历史文件）
    private ArrayList<MyFile> selectRemotePictures = new ArrayList<>();//选择的历史图片 文件
    private ArrayList<MyFile> selectRemoteVideos = new ArrayList<>();//选择的历史 视频文件
    private ArrayList<MyFile> selectLocalPictures = new ArrayList<>();//选择的本地 图片文件
    private ArrayList<MyFile> selectLocalVideos = new ArrayList<>();//选择的本地 视频文件
    private ArrayList<Photo> selectPhotos = new ArrayList<>();//本地圖片 path 集合
    private boolean isSave;
    private Date startDate;//拍卖开始时间
    private Date stopDate;//拍卖结束时间
    private boolean locationSuccess;
    private boolean hasNotch;
    private MoneyInputCheck inputCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_topic);
        //StatusBarCompat.translucentStatusBar(this, true);

        ButterKnife.bind(this);

        NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                hasNotch = notchScreenInfo.hasNotch;
                Log.i(TAG, "Is this screen notch? " + hasNotch);
                if (hasNotch) {
                    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);在刘海屏手机上，这行代码会让状态栏变为黑色，
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏，在刘海屏手机上不能按一下代码设置为全屏，因为按一下代码设置为全屏之后，再全屏预览大图的方法中，
                    //执行了 “ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);”这代码，会让屏幕抖动
                    SoftKeyboardFixerForFullscreen.assistActivity(PublishTopicActivity.this);
                    setupStartBar();
                    int statusBarHeight = Utils.getStatusBarHeight(PublishTopicActivity.this);
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }
                previewSelectFilePageView.init(totalSelectFile, PublishTopicActivity.this, hasNotch);
            }
        });


        // widthpixels = getResources().getDisplayMetrics().widthPixels;
        density = getResources().getDisplayMetrics().density;
        // heightpixels = (int) ((float) getResources().getDisplayMetrics().heightPixels - 32.0F * getResources().getDisplayMetrics().density);
        picturesListView.init(totalSelectFile, this);

        initTitleBar();
        sv_container.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                hideSoftKeyboard();
            }
        });

        AgreementDialog agreement = new AgreementDialog(this, R.array.create_topic_agreement);
        agreement.setCanceledOnTouchOutside(false);
        agreement.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        agreement.show();
        //控制dialog 的宽高，必须放在 show 之后
        WindowManager.LayoutParams params = agreement.getWindow().getAttributes();//获取对话框当前的参数值
//        params.height = (int) (screenHeight * 0.9);
        params.width = (screenWidth);
        agreement.getWindow().setAttributes(params);

    }


    private void initTitleBar() {
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPress();
            }
        });
        RelativeLayout.LayoutParams rightImagelayoutParams = new RelativeLayout.LayoutParams((int) (30 * density), (int) (30 * density));
        rightImagelayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        titleBar.getRightImage().setLayoutParams(rightImagelayoutParams);
        titleBar.setRightTitle("分类");
        final List<String> menuItems = new ArrayList<>();
        menuItems.add(EditTopicActivity.TOPIC_TYPE_EXPOSE);
        menuItems.add(EditTopicActivity.TOPIC_TYPE_REWARD);
        //  menuItems.add(EditTopicActivity.TOPIC_TYPE_OTHER);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_FIND_SOME_THING);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_FOUND);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_GIFT);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_GOODS);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_AUCTION);
//        menuItems.add(EditTopicActivity.TOPIC_TYPE_SHOW);
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyboard();
                final ListPopupWindow listPopupWindow = new ListPopupWindow(PublishTopicActivity.this);
                listPopupWindow.setAdapter(new MenuArrayAdapter(PublishTopicActivity.this, R.layout.right_menu_item, R.id.tv_dialog_item, menuItems));
                listPopupWindow.setAnchorView(titleBar.getRightLayout());
                listPopupWindow.setWidth(Utils.dpToPx(100, PublishTopicActivity.this));
                listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
                listPopupWindow.setHorizontalOffset(Utils.dpToPx(-5, PublishTopicActivity.this));
                listPopupWindow.setVerticalOffset(Utils.dpToPx(3, PublishTopicActivity.this));
                listPopupWindow.setDropDownGravity(Gravity.END);//设置对齐方式。
                listPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.tx_pop_bg_1));
                listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (menuItems.get(position)) {
                            case EditTopicActivity.TOPIC_TYPE_EXPOSE:
                                topicType = Constant.TOPIC_TYPE_EXPOSE;
                                break;
                            case EditTopicActivity.TOPIC_TYPE_REWARD:
                                topicType = Constant.TOPIC_TYPE_REWARD;
                                break;
//                            case EditTopicActivity.TOPIC_TYPE_FIND_SOME_THING:
//                                topicType = Constant.TOPIC_TYPE_REWARD;
//                                break;
                            case EditTopicActivity.TOPIC_TYPE_FOUND:
                                topicType = Constant.TOPIC_TYPE_FOUND;
                                break;

                            case EditTopicActivity.TOPIC_TYPE_GIFT:
                                topicType = Constant.TOPIC_TYPE_GIFT;
                                break;
                            case EditTopicActivity.TOPIC_TYPE_SHOW:
                                topicType = Constant.TOPIC_TYPE_SHOW;
                                break;
                            case EditTopicActivity.TOPIC_TYPE_GOODS:
                                topicType = Constant.TOPIC_TYPE_GOODS;
                                break;
                            case EditTopicActivity.TOPIC_TYPE_AUCTION:
                                topicType = Constant.TOPIC_TYPE_AUCTION;
                                break;
                            case EditTopicActivity.TOPIC_TYPE_OTHER:
                                topicType = Constant.TOPIC_TYPE_OTHER;
                                break;

                        }
                        showType(topicType);
                        listPopupWindow.dismiss();

                    }
                });
                listPopupWindow.show();

            }
        });
    }

    private void showType(int topicType) {

        switch (topicType) {
            case Constant.TOPIC_TYPE_EXPOSE:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_EXPOSE);
                hidePriceLayout();
                break;

            case Constant.TOPIC_TYPE_REWARD:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_REWARD);
                tv_priceTag.setText("悬赏金：");
                et_normalPrice.setHint("输入悬赏金额");
                showNormalPriceLayout();
                hideAcutionPriceLayout();
                initMoneyInputLister();
                break;
            case Constant.TOPIC_TYPE_FOUND:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_FOUND);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_GIFT:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_GIFT);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_GOODS:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_GOODS);
                tv_priceTag.setText("售价：");
                et_normalPrice.setHint("输入出售金额");
                showNormalPriceLayout();
                hideAcutionPriceLayout();
                break;
            case Constant.TOPIC_TYPE_AUCTION:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_AUCTION);
                tv_priceTag.setText("起拍价：");
                et_normalPrice.setHint("输入拍卖的底价");
                showAcutionPriceLayout();
                showNormalPriceLayout();
                break;
            case Constant.TOPIC_TYPE_SHOW:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_SHOW);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_OTHER:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_OTHER);
                hidePriceLayout();
                break;

        }
    }

    private void initMoneyInputLister() {

        if (inputCheck != null) {
            return;
        }
        inputCheck = new MoneyInputCheck(this, 0.01, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                et_normalPrice.setError(message);
                btn_publish.setEnabled(false);
            }

            @Override
            public void waitInput() {
                // btn_publish.setEnabled(false);
            }

            @Override
            public void inputRight() {
                btn_publish.setEnabled(true);
            }
        });

        et_normalPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputCheck.afterTextChanged(s);
            }
        });

    }

    private void showNormalPriceLayout() {
        //if (rl_NormalPrice.getVisibility() != View.VISIBLE) {
        if (!rl_NormalPrice.isShown()) {
            rl_NormalPrice.setVisibility(View.VISIBLE);
        }
    }

    private void hidePriceLayout() {
        hideNormalPriceLayout();
        hideAcutionPriceLayout();
    }

    private void hideNormalPriceLayout() {
        if (rl_NormalPrice.isShown()) {
            rl_NormalPrice.setVisibility(View.GONE);
        }
    }

    private void hideAcutionPriceLayout() {
        if (ll_auction.isShown()) {
            ll_auction.setVisibility(View.GONE);
        }
    }

    private void showAcutionPriceLayout() {
        if (!ll_auction.isShown()) {
            ll_auction.setVisibility(View.VISIBLE);
        }
    }

    private void initLocation() {
        Log.i(TAG, "initLocation: 准备定位，，，");
        location = new GaodeLocationClient(this, true);
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(AMapLocation location) {
                Log.i(TAG, "initLocation: 定位成功 ，经纬度：" + location.getLatitude() + "   " + location.getLongitude() + "位置：" + location.getAddress());
                locationSuccess = true;
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                str_address = location.getAddress();
                tv_address.setText(str_address);
            }
        });
    }


    @OnClick(R.id.ll_date_choose)
    void dateChoose() {
        DateChooseDialog dateChooseDialog = new DateChooseDialog(this);
        dateChooseDialog.setOnDateChooseListener(new DateChooseDialog.DateChooseInterface() {
            @Override
            public void getDateTime(Date startDate, Date stopDate) {
                PublishTopicActivity.this.startDate = startDate;
                PublishTopicActivity.this.stopDate = stopDate;
                tv_startDate.setText(DateUtils.dateToString(startDate, "yyyy-MM-dd HH:mm"));
                tv_stopDate.setText(DateUtils.dateToString(stopDate, "yyyy-MM-dd HH:mm"));
            }
        });
        dateChooseDialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
        dateChooseDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dateChooseDialog.show();
    }


    private void startRecordVideo() {
        long SDCardRemainMB = FileUtils.getSDFreeSize();
        if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
            showToast(getString(R.string.aliwx_no_enough_sdcard_size));
            return;
        }


        //ShortVideoKitProcesser.showRecordShortVideo(PublishTopicActivity.this, null, REQUEST_CODE_RECORD_VIDEO, SITUATION_FOR_PUBLISH, "high", 0, 0);//阿里百川短视频录制
        //startActivityForResult(new Intent(this, VideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        // startActivityForResult(new Intent(this, FFmpegVideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        VideoRecordActivityV3.startActivity(this, REQUEST_CODE_RECORD_VIDEO, true);
    }

    private void showVideo(String videoPath) {
        Uri uri = Uri.parse("http://svideo.m.taobao.com/av/implayer.html");
        Intent intent = new Intent("android.intent.action.VIEW", uri, PublishTopicActivity.this, MyVideoPlayActivity.class);
        intent.putExtra("videoPath", videoPath);
        intent.putExtra("framePicPath", framePicPath);
        intent.putExtra("videoSize", videoSize);
        startActivity(intent);
    }


    @OnClick(R.id.rl_location)
    void location() {
        Intent intent = new Intent(PublishTopicActivity.this, PickLocationMapActivity.class);
        if (latLng != null) {
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LATITUDE, latLng.getLatitude());
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LONGITUDE, latLng.getLongitude());
        }
        startActivityForResult(intent, REQUEST_CODE_LOCATION);
    }

    @OnClick(R.id.rl_description)
    void desc() {
        et_content.setFocusable(true);
        et_content.setFocusableInTouchMode(true);
        et_content.requestFocus();
        inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @OnClick(R.id.btn_publish)
    void publishTopic() {
        if (ClickUtil.isFastClick()) {
            return;
        }
        hideSoftKeyboard();
        if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
            startActivity(new Intent(PublishTopicActivity.this, LoginActivity.class).putExtra("EXTRA_CONTENT", "发布信息需要先登录"));
            return;
        }
        if (topicType == null) {
            showToast(btn_publish, "请在右上角选择分类");
            return;
        }
        String str_goodsTitle = et_title.getText().toString().trim();
        if (TextUtils.isEmpty(str_goodsTitle)) {

            // Toast.makeText(PublishTopicActivity.this, "商品标题还没设置哦", Toast.LENGTH_LONG).show();
            showToast(btn_publish, "标题没设置");
            return;
        }
        String str_content = et_content.getText().toString().trim();
        if (totalSelectFile.size() == 0) {

            showToast(btn_publish, "视频和图片不能同时为空");
            return;
        }
        String str_normalPrice = et_normalPrice.getText().toString().trim();
        double normalPrice = Utils.moneyFormatStringToDouble(str_normalPrice);
        if (topicType == Constant.TOPIC_TYPE_GOODS && TextUtils.isEmpty(str_normalPrice)) {
            showToast(btn_publish, "价格还没设置");
            return;
        }
        if (topicType == Constant.TOPIC_TYPE_REWARD) {
            if (Double.compare(normalPrice, 0.0) <= 0) {
                showToast(btn_publish, "悬赏金额还没有设置");
                return;
            }
            topic.setPrice(normalPrice);
//            ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "悬赏金没有设置，将自动设置为0", true);
//            dialog.show();
//            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                @Override
//                public void confirm() {
//                    et_normalPrice.setText("0");
//                    publishGoods();
//                }
//            });
//
//            return;
        } else if (topicType == Constant.TOPIC_TYPE_AUCTION) {
            if (Double.compare(normalPrice, 0.0) <= 0) {
                showToast(btn_publish, "起拍价没设置");
                return;
            }
            String str_deposit = et_deposit.getText().toString();
            if (TextUtils.isEmpty(str_deposit)) {
                showToast(btn_publish, "商品保证金没设置");
                return;
            }
            String str_bidIncrement = et_bidIncrement.getText().toString();
            if (TextUtils.isEmpty(str_bidIncrement)) {
                showToast(btn_publish, "商品加价幅度没设置");
                return;
            }

            if (startDate == null) {
                showToast(btn_publish, "开拍时间没设置");
                return;
            }
            // TODO: 2019/4/5 暂时注释 方便测试
            //判断结束时间是否在当前时间之后5分钟
//            if (stopDate.getTime()-System.currentTimeMillis()<5*60*1000) {
//                showToast(btn_publish, "拍卖结束时间应该在当前时间点5分钟之后");
//                return;
//            }
            topic.setPrice(normalPrice);
            topic.setAuctionPrice(Utils.moneyFormatStringToDouble(str_normalPrice));
            topic.setDeposit(Utils.moneyFormatStringToDouble(str_deposit));
            topic.setBidIncrement(Utils.moneyFormatStringToDouble(str_bidIncrement));
            topic.setStartTime(startDate);
            topic.setStopTime(stopDate);
        }
//        if (!TextUtils.isEmpty(str_normalPrice)) {
//            topic.setPrice(Double.valueOf(str_normalPrice));
//        }
        if (!TextUtils.isEmpty(str_content)) {
            topic.setContent(str_content);
        }
        //因为是保存在ES里面，所以每条发布的信息里面，都冗余保存发布者信息，这样应该是不科学的，只是ES 里面的关联查询官方文档说当数据量大了会严重影响性能
        User loginUser = UserProfileManager.getInstance().getLoginUserInfo();
        topic.setTitle(str_goodsTitle);
        User author = new User(loginUser.getuId());
        author.setAvatar(loginUser.getAvatar());
        author.setUsername(loginUser.getUsername());
        topic.setManager(author);
        topic.setStatus(Constant.TOPIC_STATUS_NORMAL);
        topic.setType(topicType);
        if (latLng != null) {
            topic.setLocation(latLng);
            topic.setAddress(str_address);
        } else {
            topic.setAddress(UserProfileManager.getInstance().getUserArea());
        }
        if (topicType == Constant.TOPIC_TYPE_REWARD) {
            if (TextUtils.isEmpty(str_normalPrice)) {
                showToast(btn_publish, "悬赏金额还没有设置");
                return;
            }
            Double reward = Double.valueOf(str_normalPrice);
            topic.setPrice(reward);
            new PayUtils(this, reward, "发布悬赏 将产生保证金",true, new PayUtils.InteractionListener() {
                @Override
                public void onPrepareComplete(String payPassword) {

                    fileUpload(payPassword);
                }
            });

        } else {

            fileUpload(null);
        }

    }

    private void fileUpload(String payPassword) {
        FileUpLoad fileUpLoad = new FileUpLoad(PublishTopicActivity.this, totalSelectFile, new FileUpLoad.InteractionListener() {
            @Override
            public void onShowToast(String content) {
                showToast(btn_publish, content);
            }

            @Override
            public void onShowProgressBar(String content) {
                showProgressDialog(content);
            }

            @Override
            public void onHideProgressBar() {
                hideProgressDialog();
            }

            @Override
            public void onUploadComplete() {
                saveToService(payPassword);
            }
        });
        fileUpLoad.run();
    }


    /**
     * 保存topic到自己服务器--ES中
     */
    private void saveToService(String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
        }
        btn_publish.setEnabled(false);
        showProgressDialog("正在保存...");
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，包括远程的，已经成功的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        topic.setId(null);//清空id 避免连续发布的时候，id出现冲突
        topic.setMyFileList(uploadList);
        Map<String, Object> body = new HashMap<>();
        body.put("topic", topic);
        if (topic.getType() == Constant.TOPIC_TYPE_REWARD) {
            if (payPassword != null) {
                body.put("payPassword", payPassword);
            }
            publishRewardTopic(uploadList, body);
        } else {
            publishTopic(uploadList, body);
        }
    }


    /**
     * 发布悬赏
     *
     * @param uploadList
     * @param body
     */
    private void publishRewardTopic(List<MyFile> uploadList, Map<String, Object> body) {
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .publishRewordTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        // progressBar.setVisibility(View.GONE);
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            btn_publish.setEnabled(true);
                            Log.e(TAG, "发布悬赏失败：" + response.message());
                            showToast(btn_publish, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "发布悬赏失败：" + result.getMsg());
                            btn_publish.setEnabled(true);
                            if (result.getStatus() == Constant.PAY_PASSWORD_ERROR) {
                                showToast(btn_publish, getString(R.string.pay_password_error));
                                updateFileStatus(uploadList);
                            } else {
                                showToast(btn_publish, getString(R.string.system_busy));
                            }
                            return;
                        }
                        updateFileStatus(uploadList);
                        Object data = result.getData();
                        if (data == null) {
                            return;
                        }
                        JSONObject resultData = (JSONObject) data;
                        Log.d(TAG, "发布悬赏完成" + resultData.toString());
                        String topicId = resultData.getString("topicId");
                        topic.setId(topicId);
                        isSave = true;
                        Double deposit = resultData.getDouble("deposit");
                        UserProfileManager.getInstance().setDeposit(deposit);
                        onPublishComplete(uploadList);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_publish.setEnabled(true);
                        Log.e(TAG, "发布悬赏失败：" + t.getMessage());
                        t.printStackTrace();
                        hideProgressDialog();
                        showToast(btn_publish, getString(R.string.system_busy));
                    }
                });

    }

    private void publishTopic(List<MyFile> uploadList, Map<String, Object> body) {
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .index(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        // progressBar.setVisibility(View.GONE);
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            btn_publish.setEnabled(true);
                            Log.e(TAG, "发布主题失败：" + response.message());
                            showToast(btn_publish, getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "发布主题失败：" + result.getMsg());
                            btn_publish.setEnabled(true);
                            showToast(btn_publish, getString(R.string.system_busy));
                            return;
                        }
                        updateFileStatus(uploadList);
                        String topicId = result.getData().toString();
                        topic.setId(topicId);
                        Log.d(TAG, "发布主题完成" + topicId);
                        isSave = true;
                        //判断发布的主题是否为悬赏任务
                        if (topic.getType() == Constant.TOPIC_TYPE_REWARD) {
                            //将用户的预支付金额增加
                            Double deposit = UserProfileManager.getInstance().getDeposit();
                            UserProfileManager.getInstance().setDeposit(deposit + topic.getPrice());
                        }
                        onPublishComplete(uploadList);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_publish.setEnabled(true);
                        Log.e(TAG, "发布主题失败：" + t.getMessage());
                        t.printStackTrace();
                        hideProgressDialog();
                        showToast(btn_publish, getString(R.string.system_busy));
                    }
                });
    }

    private void onPublishComplete(List<MyFile> uploadList) {
        ConfirmDialog confirmDialog = new ConfirmDialog(PublishTopicActivity.this, "发布完成", "去看看发布后的效果？", true);
        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                List<String> pictures = new ArrayList<>();
                for (MyFile myFile : uploadList) {
                    if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                        pictures.add(myFile.getUrl());
                    } else {
                        topic.setVideo(myFile.getUrl());
                        topic.setVideoCover(myFile.getVideoCover());
                    }
                }
                topic.setPictures(pictures);
                topic.setuId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                Intent intent = new Intent(PublishTopicActivity.this, TopicDetailsActivity.class);
                intent.putExtra(Constant.EXTRA_INFO_TOPIC, topic);
                startActivity(intent);
                finish();
            }
        });

        confirmDialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                onBackPress();
            }
        });
        confirmDialog.show();
    }

    /**
     * 保存到服务后，把已经保存的图片的状态设置为 远程图片
     * 不然连续发布，服务端把图片当成新上传图片传，插入到数据库被报ID重复的错
     *
     * @param uploadList
     */
    private void updateFileStatus(List<MyFile> uploadList) {
        for (MyFile myFile : uploadList) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                myFile.setStatus(MyFile.FILE_STATUS_REMOTE);
                //从本地文件选择集合中  移动到  远程文件选择集合中，并刷新
                if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                    selectLocalPictures.remove(myFile);
                    selectRemotePictures.add(myFile);
                } else {
                    selectLocalVideos.remove(myFile);
                    selectRemoteVideos.add(myFile);
                }
                picturesListView.refresh();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PICTURE_CHOOSE:

                ArrayList<MyFile> pictureFiles = data.getParcelableArrayListExtra("pictureFiles");
                ArrayList<MyFile> videoFiles = data.getParcelableArrayListExtra("videoFiles");
                totalSelectFile.removeAll(selectRemoteVideos);
                selectRemoteVideos.clear();
                if (videoFiles != null && videoFiles.size() != 0) {
                    selectRemoteVideos.addAll(videoFiles);
                    totalSelectFile.addAll(0, videoFiles);
                    // picturesListView.refreshVideoItem(videoFiles.get(0));
                }
                totalSelectFile.removeAll(selectRemotePictures);
                selectRemotePictures.clear();
                if (pictureFiles != null && pictureFiles.size() != 0) {
                    selectRemotePictures.addAll(pictureFiles);
                    totalSelectFile.addAll(pictureFiles);
                }
                picturesListView.refresh();

                break;

            case REQUEST_CODE_RECORD_VIDEO:

//                    int duration = data.getIntExtra("dur", 0);
                framePicPath = data.getStringExtra("coverPath");

//                int size = 0;
//                if ((new File(framePicPath)).isFile()) {
//                    File file = new File(framePicPath);
//                    size = (int) file.length();
//
//
//                    String str_size = "";
//                    if (size > 1024 * 1024) {
//                        int sizeM = size / (1024 * 1024);
//                        String remainder = String.valueOf(size % (1024 * 1024)).substring(0, 2);//取两位数
//                        str_size = sizeM + "." + remainder + "M";
//                    } else if (size > 1024) {
//                        int sizeK = size / 1024;
//                        str_size = sizeK + "KB";
//                    } else {
//                        str_size = size + "B";
//                    }
//
//                    Log.i(TAG, "onActivityResult: 封面图片大小是：" + str_size);
//
//
//                }
                //视频本地路径
                String localVideoPath = data.getStringExtra("videoPath");
                videoSize = data.getIntExtra("videoSize", 0);
                totalSelectFile.removeAll(selectLocalVideos);
                selectLocalVideos.clear();
                MyFile localVideoFile = new MyFile(localVideoPath, framePicPath, MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_LOCAL);
                selectLocalVideos.add(localVideoFile);
                totalSelectFile.addAll(0, selectLocalVideos);//插到第一个的位置
                picturesListView.refresh();
                break;

            case REQUEST_CODE_LOCATION:
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                latLng.setLatitude(latitude);
                latLng.setLongitude(longitude);
                str_address = data.getStringExtra("address");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_address.setText(str_address);
                    }
                });
                Log.d(TAG, "onActivityResult: 收到定位回传");
                break;
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);

    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        PermissionsUtils.getInstance().clear();
        if (location != null) {
            location.clear();
        }
    }

    @Override
    public void onSelectRemoteFile() {
        ArrayList<MyFile> historySelectFile = new ArrayList<>();
        historySelectFile.addAll(totalSelectFile);//添加总的
        historySelectFile.removeAll(selectLocalVideos);
        historySelectFile.removeAll(selectLocalPictures);

        MyFileSelectActivity.startActivity(this, videoLimit - selectLocalVideos.size(), pictureLimit - selectLocalPictures.size(), false, historySelectFile, REQUEST_CODE_PICTURE_CHOOSE);

    }

    @Override
    public void onPickNewPicture(int position) {
        // TODO: 2019/7/4
//        Matisse.from(PublishTopicActivity.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
//                .showSingleMediaType(true)
//                .maxSelectable(pictureLimit - selectRemotePictures.size())
//                .theme(R.style.choose_pictures_style)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);

        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setSelectedPhotos(selectPhotos)
                .setCount(9)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        selectPhotos = photos;
                        totalSelectFile.removeAll(selectLocalPictures);
                        selectLocalPictures.clear();
                        for (Photo photo : photos) {
                            selectLocalPictures.add(new MyFile(photo.uri, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_LOCAL));
                        }
                        totalSelectFile.addAll(selectLocalPictures);
                        picturesListView.refresh();
                        previewSelectFilePageView.refresh();
                    }
                });

    }

    @Override
    public void onShowBigImage(MyFile targetFile, Info info) {


        //StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.transparent));
        previewSelectFilePageView.showBigPictures(totalSelectFile.indexOf(targetFile), info);

//        filePreviewDialog = SelectFilePreviewDialog.newInstance(totalSelectFile, totalSelectFile.indexOf(targetFile), info);
//        filePreviewDialog.show(getSupportFragmentManager(), "");
//        filePreviewDialog.setGetPhotoViewInfoListener(this);//设置回调必须在show 之后
    }

    @Override
    public void onCreateVideo(View view, int position) {
        //拍摄短视频
        startRecordVideo();
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        //展示短视频
        showVideo(targetVideoFile.getUrl());

    }

    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        if (targetPictureFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemotePictures.remove(targetPictureFile);
        } else {
            selectLocalPictures.remove(targetPictureFile);
            //清除掉已选文件记录
            for (int i = 0; i < selectPhotos.size(); i++) {
                if (selectPhotos.get(i).uri.equals(targetPictureFile.getUri())) {
                    selectPhotos.remove(i);
                    break;
                }
            }
        }
        previewSelectFilePageView.refresh();
    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        if (targetVideoFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemoteVideos.remove(targetVideoFile);
        } else {
            selectLocalVideos.remove(targetVideoFile);
        }
        previewSelectFilePageView.refresh();
    }

    @Override
    public Info onGetPhotoViewInfo(int position) {
        MyFile myFile = totalSelectFile.get(position);
        return picturesListView.getPositionInfo(myFile);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPress();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void onBackPress() {

        if (previewSelectFilePageView.isShown()) {
            if (!previewSelectFilePageView.isShowAnimate()) {
                Info info = onGetPhotoViewInfo(previewSelectFilePageView.getCurrentItem());
                previewSelectFilePageView.hideBigPictures(info);

            }
            return;
        }
        if (isSave) {
            finish();
            return;
        }

        String content = et_content.getText().toString().trim();
        if (!TextUtils.isEmpty(content) || totalSelectFile.size() > 0) {
            ConfirmDialog dialog = new ConfirmDialog(PublishTopicActivity.this, "提醒", "放弃已经编辑好的内容？", true);
            dialog.show();
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    finish();
                }
            });
        } else {
            finish();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        //只需定位一次，不然当选择地位地址返回这个activity 之后，会重新调用定位，
        Log.i(TAG, "onGranted: 权限已经获取");
        if (!locationSuccess) {
            initLocation();
        }
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission) || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(PublishTopicActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
}
